/*  DataGatherer.Java
 * 
 *  WebCrawler Program
 *  @author Amandeep Jhajj and Craig Markham
 *  @date 26Apr2012
 */

package Crawler;
import java.util.Map;
import java.util.TreeMap;


public class DataGatherer {

	public class WordPair{
		public double my_avg;
		public int my_total;
		public WordPair(final double the_avg, final int the_total) {
			my_avg = the_avg;
			my_total = the_total;
		}
	}
	
	final private UI my_ui; 
	
	private Map<String, WordPair> my_total_WordMap;
	
	private int my_current_page;
	
	private int my_total_words;
	
	private int my_total_URL;
	
	private int my_total_time;
	
	
	private long my_start_time;
	
	
	public DataGatherer (final UI the_ui) {
		my_ui = the_ui;
		my_total_WordMap = new TreeMap<String, WordPair>();
		my_current_page = 0;
		my_total_words = 0;
		my_total_URL = 0;
		my_total_time = 0;
		my_start_time = System.currentTimeMillis();
	}
		
		public synchronized void addData (final Map<String, Integer> words,
				  final int wordCount, final int linkCount, final String webpage,
				  final int time) {
			my_current_page++;
			my_total_words += wordCount;
			my_total_URL += linkCount;
			my_total_time += time;
			
			for(String word : words.keySet()) {
				if(!my_total_WordMap.containsKey(word)){
					my_total_WordMap.put(word, new WordPair(0, 0));
				}
				WordPair wp = my_total_WordMap.get(word);
				
				wp.my_total += words.get(word);
				
				wp.my_avg = ((double) wp.my_total) / my_current_page;
			}
			
			
			ResultsString r = new ResultsString(webpage, my_current_page,
					  my_total_words / my_current_page, my_total_URL / my_current_page,
					  my_total_WordMap, my_total_time / my_current_page,
					  (int)(System.currentTimeMillis() - my_start_time));
			
			if(my_ui != null && my_current_page <= Controller.MAX_LINKS) {
					my_ui.reporterTriggered(r);
				}
			}
		
		public int getCurrPage() {
			return my_current_page;
		}




	
}
